#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "lauxlib.h"
#include "lualib.h"
#include "common.h"

typedef struct {
  unsigned int len, crc;
}LuacData;

int check_luac_code(const char *buf,unsigned int size)
{
  LuacData *data = (LuacData *)buf;
  if (size != data->len+8) {
    return -1;
  }
  return data->crc == crc32(buf+8,data->len) ? data->len : -1;
}

int main(int argc, char *argv[])
{
  file_info *f_info = read_file("../luac_crc.out");
  if (NULL == f_info) {
    return -1;
  }
  int len = check_luac_code(f_info->data, f_info->size);
  if (len < 0) {
    printf("not ok\n");
    return -1;
  }

  lua_State* L;
  if (NULL == (L = luaL_newstate())) {
    return -1;
  }
  luaL_openlibs(L);
  int status = luaL_loadbuffer(L,f_info->data+8,len,"test");
  if(status == 0) {
    status = lua_pcall(L, 0, LUA_MULTRET, 0);
  } else {
    printf("%s\n", lua_tostring(L,-1));
  }
  return 0;
}
